<template>
  <view class="sms-guide-container">
    <!-- 顶部图标区域 -->
    <view class="icon-section">
      <view class="icon-wrapper">
        <text class="main-icon">📱</text>
        <text class="sub-icon">✨</text>
      </view>
    </view>

    <!-- 标题区域 -->
    <view class="title-section">
      <text class="main-title">自动识别取件码</text>
      <text class="subtitle">让取件更便捷</text>
    </view>

    <!-- 说明文案区域 -->
    <view class="description-section">
      <view class="feature-item">
        <text class="feature-icon">🚀</text>
        <view class="feature-content">
          <text class="feature-title">自动读取</text>
          <text class="feature-desc">收到快递短信后，App 自动识别取件码</text>
        </view>
      </view>

      <view class="feature-item">
        <text class="feature-icon">⚡</text>
        <view class="feature-content">
          <text class="feature-title">快速添加</text>
          <text class="feature-desc">无需手动输入，一键添加包裹信息</text>
        </view>
      </view>

      <view class="feature-item">
        <text class="feature-icon">🔒</text>
        <view class="feature-content">
          <text class="feature-title">隐私安全</text>
          <text class="feature-desc">仅读取快递相关短信，本地处理数据</text>
        </view>
      </view>
    </view>

    <!-- 提示信息 -->
    <view class="notice-section">
      <text class="notice-icon">ℹ️</text>
      <text class="notice-text">授权后，App 可自动读取短信中的取件码，无需手动输入，体验更便捷。</text>
    </view>

    <!-- 按钮区域 -->
    <view class="button-section">
      <button class="primary-btn" @click="requestPermission">
        <text class="btn-text">前去授权</text>
      </button>

      <button class="secondary-btn" @click="skipToManual">
        <text class="btn-text-secondary">暂不，手动输入</text>
      </button>
    </view>

    <!-- 温馨提示 -->
    <view class="footer-tips">
      <text class="tips-text">此功能仅在 App 版本中可用</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isRequesting: false
    }
  },

  methods: {
    // 请求短信读取权限
    async requestPermission() {
      if (this.isRequesting) return
      this.isRequesting = true

      // 检查是否在 App 环境中
      // #ifdef APP-PLUS
      try {
        // 检查当前权限状态
        const permissionResult = await this.checkPermission()

        if (permissionResult === 'granted') {
          uni.showToast({
            title: '已获得权限',
            icon: 'success'
          })
          setTimeout(() => {
            this.navigateToAdd()
          }, 1500)
          return
        }

        // 使用 plus.android.requestPermissions 请求短信权限
        const permissionList = [
          'android.permission.READ_SMS',
          'android.permission.RECEIVE_SMS'
        ]

        plus.android.requestPermissions(
          permissionList,
          (resultObj) => {
            console.log('权限请求结果:', resultObj)
            const grantedList = Array.isArray(resultObj.granted) ? resultObj.granted : []
            const deniedList = Array.isArray(resultObj.denied) ? resultObj.denied : []
            const granted = grantedList.length > 0 && grantedList.some(p => permissionList.includes(p))

            if (granted) {
              uni.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 1500
              })

              // 保存权限状态
              uni.setStorageSync('sms_permission_granted', 'true')

              setTimeout(() => {
                this.navigateToAdd()
              }, 1500)
            } else {
              // 检查是否被永久拒绝
              const shouldShowRationale = deniedList.some(p => {
                try {
                  const main = plus.android.runtimeMainActivity()
                  return main.shouldShowRequestPermissionRationale(p)
                } catch (e) {
                  return false
                }
              })

              if (!shouldShowRationale) {
                // 被永久拒绝，需要跳转到设置
                uni.showModal({
                  title: '需要授权',
                  content: '短信权限已被拒绝，请在系统设置中手动开启短信读取权限。',
                  confirmText: '前往设置',
                  cancelText: '稍后再说',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      this.openAppSettings()
                    } else {
                      this.navigateToAdd()
                    }
                  }
                })
              } else {
                // 临时拒绝，可以再次请求
                uni.showModal({
                  title: '授权失败',
                  content: '未获得短信读取权限，您仍可手动输入取件码',
                  confirmText: '手动输入',
                  cancelText: '取消',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      this.navigateToAdd()
                    }
                  }
                })
              }
            }
          },
          (error) => {
            console.error('权限请求失败:', error)
            uni.showModal({
              title: '提示',
              content: '权限申请失败，请在系统设置中手动开启短信权限',
              confirmText: '前往设置',
              cancelText: '稍后再说',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  this.openAppSettings()
                } else {
                  this.navigateToAdd()
                }
              }
            })
          }
        )
      } catch (error) {
        console.error('权限请求异常:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      } finally {
        this.isRequesting = false
      }
      // #endif

      // #ifndef APP-PLUS
      uni.showModal({
        title: '提示',
        content: '短信读取功能仅在 App 中可用，当前环境不支持此功能',
        showCancel: false,
        success: () => {
          this.navigateToAdd()
        }
      })
      this.isRequesting = false
      // #endif
    },

    // 检查权限状态
    checkPermission() {
      return new Promise((resolve) => {
        // #ifdef APP-PLUS
        try {
          const main = plus.android.runtimeMainActivity()
          const PackageManager = plus.android.importClass('android.content.pm.PackageManager')
          const permissionList = [
            'android.permission.READ_SMS',
            'android.permission.RECEIVE_SMS'
          ]

          let allGranted = true
          for (const permission of permissionList) {
            const status = main.checkSelfPermission(permission)
            if (status !== PackageManager.PERMISSION_GRANTED) {
              allGranted = false
              break
            }
          }

          resolve(allGranted ? 'granted' : 'denied')
        } catch (error) {
          console.error('检查权限失败:', error)
          // 如果检查失败，使用 requestPermissions 来检查
          plus.android.requestPermissions(
            ['android.permission.READ_SMS', 'android.permission.RECEIVE_SMS'],
            (resultObj) => {
              const grantedList = Array.isArray(resultObj.granted) ? resultObj.granted : []
              const granted = grantedList.length > 0
              resolve(granted ? 'granted' : 'denied')
            },
            (error) => {
              console.error('检查权限失败:', error)
              resolve('denied')
            }
          )
        }
        // #endif

        // #ifndef APP-PLUS
        resolve('not_supported')
        // #endif
      })
    },

    // 打开应用设置
    openAppSettings() {
      // #ifdef APP-PLUS
      try {
        const Intent = plus.android.importClass('android.content.Intent')
        const Settings = plus.android.importClass('android.provider.Settings')
        const Uri = plus.android.importClass('android.net.Uri')
        const mainActivity = plus.android.runtimeMainActivity()

        const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
        intent.setData(uri)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        mainActivity.startActivity(intent)

        uni.showToast({
          title: '已跳转到设置',
          icon: 'none',
          duration: 2000
        })
      } catch (error) {
        console.error('打开设置失败:', error)
        uni.showToast({
          title: '无法打开设置',
          icon: 'none'
        })
      }
      // #endif
    },

    // 跳过授权，直接进入手动输入页面
    skipToManual() {
      uni.setStorageSync('sms_permission_skipped', 'true')
      this.navigateToAdd()
    },

    // 导航到添加包裹页面
    navigateToAdd() {
      uni.navigateTo({
        url: '/pages/package/add/add'
      })
    }
  }
}
</script>

<style scoped>
/* 主容器 */
.sms-guide-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 图标区域 */
.icon-section {
  margin-top: 80rpx;
  margin-bottom: 60rpx;
}

.icon-wrapper {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 0 20rpx rgba(255, 255, 255, 0);
  }
}

.main-icon {
  font-size: 100rpx;
}

.sub-icon {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 40rpx;
  animation: sparkle 1.5s ease-in-out infinite;
}

@keyframes sparkle {
  0%, 100% { opacity: 1; transform: scale(1) rotate(0deg); }
  50% { opacity: 0.6; transform: scale(1.2) rotate(180deg); }
}

/* 标题区域 */
.title-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.main-title {
  font-size: 52rpx;
  font-weight: bold;
  color: white;
  display: block;
  margin-bottom: 16rpx;
  text-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

.subtitle {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  display: block;
}

/* 说明文案区域 */
.description-section {
  width: 100%;
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.feature-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 32rpx;
}

.feature-item:last-child {
  margin-bottom: 0;
}

.feature-icon {
  font-size: 48rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.feature-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.feature-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 8rpx;
  display: block;
}

.feature-desc {
  font-size: 24rpx;
  color: #6b7280;
  line-height: 1.6;
  display: block;
}

/* 提示信息 */
.notice-section {
  width: 100%;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 60rpx;
  display: flex;
  align-items: flex-start;
  backdrop-filter: blur(10px);
}

.notice-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.notice-text {
  font-size: 24rpx;
  color: white;
  line-height: 1.8;
  flex: 1;
}

/* 按钮区域 */
.button-section {
  width: 100%;
  margin-bottom: 40rpx;
}

.primary-btn {
  width: 100%;
  height: 90rpx;
  background: white;
  border-radius: 45rpx;
  border: none;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.primary-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.btn-text {
  font-size: 32rpx;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.secondary-btn {
  width: 100%;
  height: 90rpx;
  background: transparent;
  border: 2rpx solid rgba(255, 255, 255, 0.6);
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.secondary-btn:active {
  background: rgba(255, 255, 255, 0.1);
}

.btn-text-secondary {
  font-size: 28rpx;
  color: white;
}

/* 底部提示 */
.footer-tips {
  text-align: center;
}

.tips-text {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.7);
}
</style>
